package com.mlamp.动态规划;

import java.util.Arrays;

public class 最长湍流子数组 {
    public static void main(String[] args) {

        int[] array = new int[]{9, 4, 2, 10, 7, 8, 8, 1, 9};
        //array = new int[]{9, 9};
        //array = new int[]{100, 100, 100, 100};
        int result = maxTurbulenceSize2(array);
        System.out.println(result);
    }

    public static int maxTurbulenceSize(int[] arr) {
        int length = arr.length;
        int res = 1;
        int anchor = 0;
        for (int i = 1; i < arr.length; i++) {
            int c = Integer.compare(arr[i - 1], arr[i]);
            if (i == length - 1 || c * Integer.compare(arr[i], arr[i + 1]) != -1) {
                if (c != 0) res = Math.max(res, i - anchor + 1);
                anchor = i;
            }
        }
        return res;
    }

    public static int maxTurbulenceSize2(int[] arr) {
        int length = arr.length;
        if (length == 1) return 1;
        int res = 1;
        int[] compareResult = new int[length - 1];
        for (int i = 1; i < arr.length; i++) {
            int c = Integer.compare(arr[i - 1], arr[i]);
            compareResult[i - 1] = c;
        }
        System.out.println(Arrays.toString(compareResult));
        int mxLen = 0;
        int cursor = 1;
        for (int i = 1; i < compareResult.length; i++) {
            if (compareResult[i] * compareResult[i - 1] == -1) {
                continue;
            } else {
                if (compareResult[i] * compareResult[i - 1] != -1)
                    mxLen = Math.max(mxLen, i - cursor);
                cursor = i;
            }
        }
        return mxLen;
    }


}
